<?php

namespace app\controller\common;

use app\controller\ApiBaseController;
use app\model\LawUserModel;

/**
 * oss公共方法
 */
class OssPlatform extends ApiBaseController
{

    /**
     * 批量上传文件
     */
    public function uploadfile()
    {
        try {
            $strIdCode = param_filter($this->request->param('id_code', ''), 'string');
            if (empty($strIdCode)) {
                return api_response([], '缺少用户唯一识别号', 0);
            }
            $intCaseId = param_filter($this->request->param('case_id', ''), 'int');
            if (empty($intCaseId)) {
                return api_response([], '缺少案件id', 0);
            }
            $strBusinessCode = param_filter($this->request->param('business_code', ''), 'int');
            if (empty($strBusinessCode)) {
                return api_response([], '缺少业务id', 0);
            }
            $arrFiles = $this->request->file();
            if (empty($arrFiles)) {
                return api_response([], '请选择文件', 0);
            }

            //验证id_code是否有效
            $arrUserInfo = LawUserModel::getOneByWhere([['id_code', '=', $strIdCode]]);
            if (empty($arrUserInfo)) {
                return api_response([], '非法操作，请重新登录', 0);
            }

            $arrFilePaths = [];
            $intKey = 0; //文件根据序号命名
            foreach ($arrFiles as $objFile) {
                $intKey++;
                $strFileName = $objFile->getOriginalName('name'); //上传的文件名（用来提取后缀）
                $strNewFilePath = $this->getNewFileName($intKey, $strFileName, $strIdCode, $intCaseId, $strBusinessCode);

                $boolUp = uploadToOss($objFile, $strNewFilePath);
                if (!$boolUp) {
                    return api_response([], '上传失败，请重试', 0);
                }
                $arrFilePaths[] = $strNewFilePath;
            }
            return api_response($arrFilePaths, '上传成功', 1);
        } catch (\Exception $e) {
            return api_response([], $e->getMessage(), 0);
        }
    }


    /**
     * 生成上传到oss的新文件名
     *
     * @param integer $key
     * @param string $strFileName
     * @param string $strIdCode
     * @param integer $intCaseId
     * @param string $strBusinessCode
     * @return string
     */
    private function getNewFileName(int $key, string $strFileName, string $strIdCode, int $intCaseId, string $strBusinessCode): string
    {
        // 文件根据序号重命名
        if ($key < 10) {
            $strNewFileName = '000' . $key;
        } elseif ($key < 100) {
            $strNewFileName = '00' . $key;
        } elseif ($key < 1000) {
            $strNewFileName = '0' . $key;
        } else {
            $strNewFileName = $key;
        }

        $strExt = pathinfo($strFileName, PATHINFO_EXTENSION); //获取文件后缀名
        return $strIdCode . '/' . $intCaseId . '/' . $strBusinessCode . '/' . $strNewFileName . '.' . $strExt;
    }
}
